package com.lzh.others.basejava;

import cn.hutool.core.thread.ExecutorBuilder;
import cn.hutool.core.thread.ThreadUtil;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * protected变量，成员，方法，等只对本身，本包和子类可见
 *
 * @description:
 * @author: LiuZiHao
 * @version:
 * @date: 创建时间:2023年01月16日 10:17:19
 */
public class FutureOutOfTime {

    private static final ExecutorService executorService = Executors.newSingleThreadExecutor();
    private static final ScheduledExecutorService scheduledExecutor = Executors.newScheduledThreadPool(1);
    private static final AtomicBoolean shouldContinue = new AtomicBoolean(true);

    private static final ExecutorService checkService = ThreadUtil.newSingleExecutor();

    private static final ExecutorService checkService2 =
            ExecutorBuilder.create().setCorePoolSize(4).setMaxPoolSize(4).setKeepAliveTime(0L).buildFinalizable();

    private static String[] NAME = {"任务1", "任务2", "任务3", "任务4", "任务5"};

    public static void main(String[] args) {

    }

    private static Future<Void> submitTask(String taskName) {
        Callable<Void> task = () -> {
            // 模拟耗时操作
            try {
//                String test = null;
//                if (test.equals("test")){
//                    System.out.println("test = " + test);
//                }
                Thread.sleep(1000);
            } catch (Exception e) {
                System.out.println("发生异常");
                Thread.currentThread().interrupt();
                throw new IllegalStateException("Task interrupted", e);
            }
            System.out.println("任务完成,任务名称:" + taskName);
            shouldContinue.set(false); // 任务完成时，设置标志为 false
            return null;
        };
        return executorService.submit(task);
    }

    private static void startTimeoutCheck(Future<Void> future) {
        scheduledExecutor.scheduleAtFixedRate(() -> {
            System.out.println("schedule执行中...");
            if (!future.isDone()) {
                // 如果任务在指定时间内没有完成，尝试取消它
                future.cancel(true);
                System.out.println("Task was cancelled due to timeout.");
            } else {
                // 任务已完成，设置标志为 false，定时任务将在下一次检查时停止
                shouldContinue.set(false);
            }
        }, 5, 5, TimeUnit.SECONDS);
    }

}
